package com.iot.framework.aspectj;

import com.alibaba.fastjson.JSON;
import com.iot.common.annotation.DataSource;
import com.iot.common.annotation.Log;
import com.iot.common.core.domain.BaseEntity;
import com.iot.common.core.domain.entity.SysUser;
import com.iot.common.core.domain.model.LoginUser;
import com.iot.common.enums.BusinessStatus;
import com.iot.common.enums.BusinessType;
import com.iot.common.enums.HttpMethod;
import com.iot.common.utils.DateUtils;
import com.iot.common.utils.SecurityUtils;
import com.iot.common.utils.ServletUtils;
import com.iot.common.utils.StringUtils;
import com.iot.common.utils.ip.IpUtils;
import com.iot.framework.datasource.DynamicDataSourceContextHolder;
import com.iot.framework.manager.AsyncManager;
import com.iot.framework.manager.factory.AsyncFactory;
import com.iot.system.domain.SysOperLog;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.HandlerMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Collection;
import java.util.Date;
import java.util.Map;
import java.util.Objects;

/**
 * 多数据源处理
 * 
 * @author iot
 */
@Aspect
@Component
public class RequestParamsAspect
{
    protected Logger logger = LoggerFactory.getLogger(getClass());

    @Before("@annotation(controllerLog)")
    public void preHandleParam(JoinPoint joinPoint, Log controllerLog){
        Object[] args = joinPoint.getArgs();
        if(controllerLog.businessType() == BusinessType.INSERT || controllerLog.businessType() == BusinessType.UPDATE){
            SysUser sysUser = SecurityUtils.getSysUser();
            for(Object arg : args){
                if(arg instanceof BaseEntity){
                    if(controllerLog.businessType() == BusinessType.INSERT){
                        // 插入数据添加创建人和创建时间
                        ((BaseEntity) arg).setCreateBy(sysUser.getUserName());
                        ((BaseEntity) arg).setCreateTime(DateUtils.getNowDate());
                    }else{
                        // 修改数据添加修改人和修改时间
                        ((BaseEntity) arg).setUpdateBy(sysUser.getUserName());
                        ((BaseEntity) arg).setUpdateTime(DateUtils.getNowDate());
                    }
                    break;
                }
            }
        }
    }
}
